<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Basic Layout - jQuery EasyUI Demo</title>
	<link rel="stylesheet" type="text/css" href="../css/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../css/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="../css/themes/color.css">
	<script type="text/javascript" src="../js/jquery.min.js"></script>
    <script type="text/javascript" src="../js/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="../js/jquery.serializejson.min.js"></script>

</head>
<body>
        <table id="dg"></table>
        <div id="tb" style="padding:2px 5px;">
            <input id="name" label="用户名称:" style="width:30%;">
            <a href="#" id="searchData" class="easyui-linkbutton" iconCls="icon-search">搜索</a>
            <a href="#" id="addData" class="easyui-linkbutton" data-options="iconCls:'icon-add'">添加信息</a>
            <a href="#" id="removesData" class="easyui-linkbutton" data-options="iconCls:'icon-remove'">批量删除</a>
        </div>

        <div id="dlg" class="easyui-dialog" title="添加信息" data-options="iconCls:'icon-save',closed: true" style="width:400px;height:400px;padding:10px">
                        <form id="ff" class="easyui-form" method="post" data-options="novalidate:true">
                            <input  type="hidden" name="_id" style="width:100%">
                            <div style="margin-bottom:20px">
                                <input class="easyui-textbox" name="name" style="width:100%" data-options="label:'账号:',required:true,missingMessage:'请填写账号',validType:'midLength[4,10]'">
                            </div>
                            <div style="margin-bottom:20px">
                                <input class="easyui-passwordbox"  name="password" style="width:100%" data-options="label:'密码:',required:true,missingMessage:'请填写密码',validType:'minLength[6]'">
                            </div>
                            <div style="margin-bottom:20px">
                                    <select class="easyui-combobox" name="vip" style="width:100%" data-options="label:'VIP:',required:true,missingMessage:'请选择VIP',editable:false,panelHeight:'auto'"><option value="0">普通用户</option><option value="1">VIP用户</option></select>
                            </div>

                            <div style="margin-bottom:20px">
                                <input class="easyui-textbox" name="phone" type="tel" style="width:100%" data-options="label:'手机:',required:true,missingMessage:'请填写账号',validType:'pwdLength[11]'">
                            </div>
                            <div style="margin-bottom:20px">
                                <input class="easyui-textbox" name="email" type="email" style="width:100%" data-options="label:'邮箱Email:',required:true,missingMessage:'请填写邮箱',validType:'emailLength'">
                            </div>
                            <div style="margin-bottom:20px">
                                <input class="easyui-textbox" name="address" type="text" style="width:100%" data-options="label:'地址:',required:true,missingMessage:'请填写地址'">
                            </div>
                            <div style="margin-bottom:20px">
                                <input class="easyui-textbox" name="professional" type="text" style="width:100%" data-options="label:'职业:',required:true,missingMessage:'请填写职业',validType:'chiLength'">
                            </div>
                            <div style="margin-bottom:20px">
                                <input class="easyui-numberbox"  name="age"  type="text" style="width:100%"  data-options="min:1,max:99,label:'年龄:',required:true,missingMessage:'请填写年龄'">
                            </div>
                            <div style="margin-bottom:20px">
                                <input class="easyui-tagbox" name="hobby"  value="篮球,足球"  style="width:100%" data-options="label:'爱好:',required:true,missingMessage:'请填写爱好'">
                            </div>


                        </form>
                        <div style="text-align:center;padding:5px 0">
                            <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()" style="width:80px">提交</a>
                            <a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()" style="width:80px">清除</a>
                        </div>
        </div>


        <div id="dlg1" class="easyui-dialog" title="详细信息" data-options="iconCls:'icon-save',closed: true" style="width:400px;height:350px;padding:10px">
            <p>详细信息：</p>
            <p id="usertext"></p>
        </div>
</body>
</html>

<script>
    //console.log(window.parent.globalURL);
 function submitForm(){
    $('#ff').form('submit',{
        onSubmit:function(){
           if($(this).form('enableValidation').form('validate')){
                // 将当前页面的表单信息进行获取，然后进行ajax请求
                var formData = $("#ff").serializeJSON();
                //console.log(formData._id.length);
                if(formData._id.length > 0){
                    // update
                    $.ajax({
                        url:`${window.parent.globalURL}users/${formData._id}`,
                        type:'put',
                        data: formData
                    }).done(function(res){
                        $('#dlg').dialog('close');
                        $('#dg').datagrid('reload');
                        $('#ff').form('clear');
                    })
                }else{
                    // add
                    delete formData._id;
                    $.ajax({
                        url:`${window.parent.globalURL}users`,
                        type:'post',
                        data: formData
                    }).done(function(res){
                        $('#dlg').dialog('close');
                        $('#dg').datagrid('reload');
                        $('#ff').form('clear');
                    })
                }
            }
         return false   // 表单验证
        }
    });
}

function clearForm(){
    $('#ff').form('clear');
};

$('#dg').datagrid({
    url:`${window.parent.globalURL}users/list`,
    fit:'true',
    border:false,
    pagination:true,
    toolbar:'#tb',
    onLoadSuccess:function(data){$("a[name='a1']").linkbutton({plain:true})},
    columns:[[
        {field:'ck',checkbox:true},
        {field:'name',title:'用户名',width:120},
        {field:'password',title:'密码',width:120},
        {field:'vip',title:'会员',width:100,formatter: function(value, row, index) {
                    return `<span>${vip(row.vip)}</span>`;
                }},
        {field:'phone',title:'手机号码',width:150},
        {field:'email',title:'电子邮箱',width:150},
        {field:'_id',title:'操作', width:160,
            formatter: function(value,row,index){
                return `<a href="javascript:void(0)" name="a1" class="c3"  onclick="updateData('${row._id}')">修改</a> <a href="javascript:void(0)" name="a1" class="c7" onclick="deleteData('${row._id}')">删除</a>
                <a href="javascript:void(0)" name="a1" class="c8"  onclick="showData('${row._id}')">详情</a>`
			}
		}
    ]]
});
function deleteData(id){

    $.messager.confirm('确认对话框', '你确认删除?', function(r){
        if (r){

            $.ajax({
                url:`${window.parent.globalURL}users/${id}`,
                type:'delete'
            }).done(function(res){
                $("#dg").datagrid('reload');
            })
        }
    });

}

function updateData(id){
    $.ajax({
        url:`${window.parent.globalURL}users/${id}`,
        type:'get'
    }).done(function(res){
        $('#ff').form('load',res);
        $('#dlg').dialog('open');
    })
}
function vip(boolean){
    var str='';
    if(boolean==true){
       str='VIP会员';
    }else{
        str='普通用户'
    }
    return str
}
function renderTime(date) {
        var dateee = new Date(date).toJSON();
        return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
    }
function showData(id){
    $.ajax({
        url:`${window.parent.globalURL}users/${id}`,
        type:'get'
    }).done(function(res){
        console.log(res);
        var str = `<p>账号：${res.name}</p><p>密码：${res.password}</p><p>手机：${res.phone}</p><p>邮箱：${res.email}</p><p>会员：${vip(res.vip)}</p><p>年龄：${res.age}</p><p>职业：${res.professional}</p><p>地址：${res.address}</p><p>爱好：${res.hobby}</p><p>注册日期：${renderTime(res.date)}</p>`
        $('#dlg1 #usertext').html(str);
        $('#dlg1').dialog('open');
    })
}
function deleteDatas(){
  var rows = $('#dg').datagrid('getSelections');
  var ids = [];
  for(var i=0;i<rows.length;i++){
    ids.push(rows[i]._id);
  }

  $.messager.confirm('确认对话框', '你确认删除?', function(r){
        if (r){
            $.ajax({
                url:`${window.parent.globalURL}users/removes`,
                type:'post',
                data:{
                    ids: ids.toString()
                }
            }).done(function(res){
                $("#dg").datagrid('reload');
            })
        }
    });


}

$("#searchData").click(function(){
    $('#dg').datagrid({
        queryParams: {
            name: $("#name").val()
        }
    });
})


$("#addData").click(function(){
    $('#dlg').dialog('open');
})

$("#removesData").click(function(){
    deleteDatas();
});

$(function(){
    $.extend($.fn.validatebox.defaults.rules, {
            minLength: {
                validator: function(value, param){
                return value.length >= param[0];
                },
                message: '密码最低6位'
            },
            midLength:{
                validator: function(value, param) {
                return value.length >= param[0] && value.length <= param[1];
                },
                message: '用户名必须在4到10位之间!'
            },
            pwdLength: {
                validator: function(value, param) {
                return value.length == param[0]&&(/^1[34578]\d{9}$/.test(value));
                },
                message: '手机号码必须是11位数字'
            },
            emailLength: {
                validator: function(value, param) {
                return (/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(value));
                },
                message: '请输入一个正确的邮箱'
            },
            numLength: {
                validator: function(value, param) {
                return (/^[1-9]\d{0,2}$/.test(value));
                },
                message: '请输入正确年龄前面不要加0'
            },
            chiLength: {
                validator: function(value, param) {
                return (/^[\u4e00-\u9fa5]{1,10}$/.test(value));
                },
                message: '请输入中文职业1到10个字'
            }
        });
});

</script>